package Controller;

import Data.*;
import MyInterfaces.MassageType;
import Service.Main;
import Service.SendFile;
import Service.SendMassage;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.text.Font;
import javafx.scene.text.Text;
import javafx.scene.text.TextAlignment;
import javafx.scene.text.TextFlow;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javafx.util.Callback;

import java.awt.*;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GroupStage {

    @FXML
    private ToggleButton submitButton;

    @FXML
    private TextArea GetMassage;

    @FXML
    private ToggleButton emoji;

    @FXML
    private TextField group_name;

    @FXML
    private ScrollPane staticScroll;

    @FXML
    private ToggleButton put_friend;

    @FXML
    private ToggleButton out_group;

    @FXML
    private ToggleButton SendMassage;

    @FXML
    private ImageView group_avatar;

    @FXML
    private FlowPane dynamicEmoji;

    @FXML
    private Tab nodynamic;

    @FXML
    private ToggleButton fileButton;

    @FXML
    private Text group_id;

    @FXML
    private Tab dynamic;

    @FXML
    private FlowPane nodynamicEmoji;

    @FXML
    private ScrollPane SeeEmoji;

    @FXML
    private ScrollPane dynamicScroll;

    @FXML
    private ListView<MassageData> MassageList;
    private ObservableList<MassageData> MassageOblist;
    @FXML
    private TextArea group_saying;

    @FXML
    private ResourceBundle resources;

    @FXML
    private URL location;


    @FXML
    private Button GetMoreMassage;

    @FXML
    private ToggleButton delete_group;

    private ChatData mydata;

    private Image myavatar;

    public void setMyavatar(Image myavatar) {
        this.myavatar = myavatar;
    }

    private GroupData data;

    private HashMap<String,GroupFriendData> friendmap=new HashMap<>();

    public void setData(GroupData data) {
        this.data = data;
        //需要把相关联的数据全部换掉，比如arrylist和hashmap
    }

    public void changeFriendMap(String id, GroupFriendData groupFriendData)
    {
        System.out.println("收到了好友的信息");
        int k=friendArryList.indexOf(friendmap.get(id));
        friendArryList.remove(k);
        friendArryList.add(groupFriendData);
        friendmap.put(id,groupFriendData);

        ChatMain chatMain=Main.AllContronller.getChatMainController();
        chatMain.AddGroupFriendList(data.getGroup_id(),friendArryList);

        PrivateInformation privateInformation=Main.AllContronller.getPrivateInformationControllerById(id);
        if(privateInformation!=null)
        {
            getInformation(data.getIdentity(),groupFriendData,privateInformation);
        }
    }

    @FXML
    void SendFile(ActionEvent event) throws IOException, NoSuchAlgorithmException {

        Stage stage=new Stage();
        File file;
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择文件");

        fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))
        );

        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("All ", "*.*")
        );
        file= fileChooser.showOpenDialog(stage);

        if(file!=null) {
        //    已经读取好了
        //   先发送一个我需要上传文件的消息
            event massage=new event();
            massage.setType(MassageType.Send_File_To_Group);
            GroupMassageData groupMassageData=new GroupMassageData();
            MassageData massageData;
            SendFile sendFile=new SendFile(file.getAbsolutePath());
            massageData=sendFile.sendToFile();

            massageData.setSender(data.getId());
            massageData.setReceiver(data.getGroup_id());

            massageData.setTimestamp(new Timestamp(System.currentTimeMillis()));
            massageData.setMD5(getMD5(file));
            massageData.setFile_name(file.getName());
            massageData.setIs_file(1);

            String suffixname=null;

            if(file!=null)
            {
                suffixname=file.getName();
                int dotIndex=suffixname.lastIndexOf('.');
                if(dotIndex>0&&dotIndex<suffixname.length()-1)
                {
                    massageData.setSuffix_name(suffixname.substring(dotIndex+1));
                    System.out.println(suffixname.substring(dotIndex+1));
                }
                else massageData.setSuffix_name("");
            }
            System.out.println("后缀名称为"+massageData.getSuffix_name());

            groupMassageData.setMassageData(massageData);
            groupMassageData.setArrayList(friendArryList);
            massage.setT(groupMassageData);

            new SendMassage().sendMassage(massage);

        }

    }
    private boolean isemoji=false;
    @FXML
    void SendEmoji(ActionEvent event) {
        if(isemoji)
        {
            isemoji=false;
            SeeEmoji.setVisible(false);
            SeeEmoji.setDisable(true);
        }
        else
        {
            isemoji=true;
            SeeEmoji.setDisable(false);
            SeeEmoji.setVisible(true);
        }
    }

    public void addOneMassage(MassageData massage)
    {
        System.out.println(massage.getSender()+"给"+massage.getReceiver()+"发送的消息"+massage.getContent()+massage.getIs_file()+massage.getFile_name());
//            MassageOblist=MassageList.getItems();
//            System.out.println(massage);
        MassageOblist.add(massage);
        MassageList.refresh();
        MassageList.scrollTo(MassageOblist.size()-1);

        MassageList.setCellFactory(new Callback<ListView<MassageData>, ListCell<MassageData>>() {
            @Override
            public ListCell<MassageData> call(ListView<MassageData> param) {
                ListCell<MassageData> list=new ListCell<MassageData>(){
                    @Override
                    protected void updateItem(MassageData arg0, boolean arg1) {
                        super.updateItem(arg0, arg1);
                        if(getIndex()==0)
                        {
                            setPrefHeight(50);
                            setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
                            HBox hBox=new HBox(30);
                            Button getmore=new Button("获得更多消息");
                            hBox.getChildren().add(getmore);
                            hBox.setAlignment(Pos.TOP_CENTER);
                            this.setGraphic(hBox);

                            getmore.setOnMouseClicked((MouseEvent event)->
                            {
                                //点击事件，是向服务器发送更多消息的请求
                                System.out.println(MassageOblist.size()-1);
                                if(MassageOblist.size()<=1)
                                {
                                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                    alert.setTitle("错误");
                                    alert.setHeaderText(null);
                                    alert.setContentText("没有更多消息了!");
                                    alert.showAndWait();
                                }
                                else
                                {
                                    Data.event massage=new event();
                                    massage.setType(MassageType.Request_Chat_Massage);
                                    Timestamp timestamp=new Timestamp(System.currentTimeMillis());

                                    MassageData massageData=new MassageData(data.getId(),data.getGroup_id(),timestamp,"");
                                    massageData.setSum(MassageOblist.size()-1);
                                    massage.setT(massageData);
                                    try {
                                        new SendMassage().sendMassage(massage);
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                            });
                        }
                        else if(arg1==false){

                            setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
                            HBox hbox=new HBox(30);
                            hbox.setAlignment(Pos.BASELINE_LEFT);//对齐显示

                            //需要头像，消息，以及日期
                            if(arg0.getSender().equals(data.getId()))
                            {
                                //代表是自己发的
                                Image image=myavatar;
                                ImageView imageView=new ImageView(image);
                                imageView.setFitWidth(50);
                                imageView.setFitHeight(50);
                                Circle circle=new Circle(25,25,25);
                                imageView.setClip(circle);

                                Timestamp timestamp=arg0.getTimestamp();
                                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm");
                                String formatted=sdf.format(timestamp);
                                Label date=new Label(formatted);


                                TextFlow content=new TextFlow();
                                if(arg0.getIs_file()==1)
                                {
                                    //说明这是文件
                                    Image fileimage=new Image("file:"+"E:\\JDK\\QQClient\\nox\\src\\img\\img_1.png");
                                    ImageView fileimageview=new ImageView(fileimage);
                                    fileimageview.setFitWidth(60);
                                    fileimageview.setFitHeight(60);

                                    Label filename=new Label(arg0.getFile_name());
                                    filename.setFont(new Font(10));
                                    VBox vBox=new VBox(10);
                                    vBox.setAlignment(Pos.TOP_RIGHT);
                                    vBox.getChildren().addAll(fileimageview,filename);

                                    HBox hBox=new HBox(20);
                                    hBox.getChildren().addAll(vBox,imageView);
                                    HBox.setHgrow(imageView,Priority.ALWAYS);
                                    HBox.setHgrow(vBox,Priority.ALWAYS);
                                    hBox.setAlignment(Pos.TOP_RIGHT);

                                    VBox vBox1=new VBox();
                                    vBox1.setAlignment(Pos.TOP_CENTER);
                                    vBox1.getChildren().addAll(date,hBox);

                                    this.setGraphic(vBox1);
                                    prefHeightProperty().bind(hBox.prefHeightProperty());

                                    hBox.setOnMouseClicked((MouseEvent event)->
                                    {
                                        //先判断本地是否已经有这个文件
                                        File newfile=new File("F:\\qqclientfile"+"\\"+arg0.getFile_name());
                                        if(newfile.exists())
                                        {
                                            //打开这个文件
                                            Desktop desktop=Desktop.getDesktop();
                                            if(desktop.isSupported(Desktop.Action.OPEN))
                                            {
                                                try {
                                                    desktop.open(newfile);
                                                } catch (IOException e) {
                                                    throw new RuntimeException(e);
                                                }
                                            }
                                            else
                                            {
                                                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                                alert.setTitle("错误");
                                                alert.setHeaderText(null);
                                                alert.setContentText("不支持打开此文件类型，请到"+newfile.getAbsolutePath()+"中查看!");
                                                alert.showAndWait();
                                            }
                                        }
                                        else
                                        {
                                            //没有就申请下载
                                            //向服务器发送请求，因为已经知道了该文件的id，发送一个请求id的代码

                                            event massage=new event();
                                            MassageData data=new MassageData();
//                                        data.setSender(arg0.getSender());
//                                        data.setReceiver(arg0.getReceiver());
                                            data.setFile_name(arg0.getFile_name());
                                            data.setFile_id(arg0.getFile_id());
                                            massage.setType(MassageType.Request_Get_File);
                                            massage.setT(data);
                                            try {
                                                new SendMassage().sendMassage(massage);
                                            } catch (IOException e) {
                                                throw new RuntimeException(e);
                                            }
                                        }

                                    });

                                }
                                else
                                {
                                    content=transfor(arg0.getContent());
                                    content.setMaxWidth(400);
                                    content.setTextAlignment(TextAlignment.RIGHT);

                                    content.setPadding(new Insets(20,20,20,20));
                                    BackgroundFill backgroundFill=new BackgroundFill(Color.LIGHTBLUE,CornerRadii.EMPTY,Insets.EMPTY);
                                    Background bg=new Background(backgroundFill);
                                    content.setBackground(bg);
                                    VBox vBox=new VBox(10);

                                    HBox hBox=new HBox(10);
                                    hBox.getChildren().addAll(content,imageView);

                                    HBox.setHgrow(imageView, Priority.ALWAYS);
                                    HBox.setHgrow(content,Priority.ALWAYS);
                                    hBox.setAlignment(Pos.TOP_RIGHT);

                                    vBox.setAlignment(Pos.TOP_CENTER);
                                    vBox.getChildren().addAll(date,hBox);
                                    this.setGraphic(vBox);
                                    prefHeightProperty().bind(vBox.prefHeightProperty());
                                }

                                imageView.setOnMouseClicked((MouseEvent event)->{
                                    //加载自己的个人信息
                                    Stage stage=new Stage();
                                    File file=new File("E:\\JDK\\QQClient\\nox\\src\\fxml\\PrivateInformation.fxml");
                                    URL location= null;
                                    try {
                                        location = file.toURI().toURL();
                                    } catch (MalformedURLException e) {
                                        throw new RuntimeException(e);
                                    }
                                    FXMLLoader fxmlLoader=new FXMLLoader();
                                    fxmlLoader.setLocation(location);
                                    Parent root= null;
                                    try {
                                        root = fxmlLoader.load();
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                    stage.setTitle("个人信息修改");
                                    stage.setResizable(false);
                                    stage.setScene(new Scene(root,400,600));
                                    stage.show();
                                    PrivateInformation privateInformation=fxmlLoader.getController();
                                    Main.AllContronller.setPrivateInformationController(privateInformation);
                                    ChatMain chatMain= Main.getAllContronller().getChatMainController();
//
                                    PrivateInformationData mydata=chatMain.getMydata();
                                    privateInformation.changeInformation(mydata);

                                    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                                        @Override
                                        public void handle(WindowEvent event) {
                                            stage.close();
                                            Main.AllContronller.setPrivateInformationController(null);
                                            //    System.out.print("监听到窗口关闭");
                                        }
                                    });
                                });
                            }
                            else
                            {
                                byte[] bytes=friendmap.get(arg0.getSender()).getAvatar();
                                Image image=new Image(new ByteArrayInputStream(bytes));
                                ImageView imageView=new ImageView(image);
                                imageView.setFitWidth(50);
                                imageView.setFitHeight(50);
                                Circle circle=new Circle(25,25,25);
                                imageView.setClip(circle);

                                Timestamp timestamp=arg0.getTimestamp();
                                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm");
                                String formatted=sdf.format(timestamp);
                                Label date=new Label(formatted);

                                TextFlow content=new TextFlow();
                                if(arg0.getIs_file()==1)
                                {
                                    //说明这是文件
                                    Image fileimage=new Image("file:"+"E:\\JDK\\QQClient\\nox\\src\\img\\img_1.png");
                                    ImageView fileimageview=new ImageView(fileimage);
                                    fileimageview.setFitWidth(60);
                                    fileimageview.setFitHeight(60);

                                    Label filename=new Label(arg0.getFile_name());
                                    filename.setFont(new Font(10));
                                    VBox vBox=new VBox(10);
                                    vBox.setAlignment(Pos.TOP_LEFT);
                                    vBox.getChildren().addAll(date,fileimageview,filename);

                                    HBox hBox=new HBox(20);
                                    hBox.getChildren().addAll(imageView,vBox);
                                    HBox.setHgrow(imageView,Priority.ALWAYS);
                                    HBox.setHgrow(vBox,Priority.ALWAYS);
                                    hBox.setAlignment(Pos.TOP_LEFT);

                                    VBox vBox1=new VBox();
                                    vBox1.setAlignment(Pos.TOP_CENTER);
                                    vBox1.getChildren().addAll(date,hBox);

                                    this.setGraphic(vBox1);
                                    prefHeightProperty().bind(hBox.prefHeightProperty());

                                    hBox.setOnMouseClicked((MouseEvent event)->
                                    {
                                        //先判断本地是否已经有这个文件
                                        File newfile=new File("F:\\qqclientfile"+"\\"+arg0.getFile_name());
                                        if(newfile.exists())
                                        {
                                            //打开这个文件
                                            Desktop desktop=Desktop.getDesktop();
                                            if(desktop.isSupported(Desktop.Action.OPEN))
                                            {
                                                try {
                                                    desktop.open(newfile);
                                                } catch (IOException e) {
                                                    throw new RuntimeException(e);
                                                }
                                            }
                                            else
                                            {
                                                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                                alert.setTitle("错误");
                                                alert.setHeaderText(null);
                                                alert.setContentText("不支持打开此文件类型，请到"+newfile.getAbsolutePath()+"中查看!");
                                                alert.showAndWait();
                                            }
                                        }
                                        else
                                        {
                                            //没有就申请下载
                                            //向服务器发送请求，因为已经知道了该文件的id，发送一个请求id的代码

                                            event massage=new event();
                                            MassageData data=new MassageData();
//                                        data.setSender(arg0.getSender());
//                                        data.setReceiver(arg0.getReceiver());
                                            data.setFile_name(arg0.getFile_name());
                                            data.setFile_id(arg0.getFile_id());
                                            massage.setType(MassageType.Request_Get_File);
                                            massage.setT(data);
                                            try {
                                                new SendMassage().sendMassage(massage);
                                            } catch (IOException e) {
                                                throw new RuntimeException(e);
                                            }
                                        }

                                    });
                                    prefHeightProperty().bind(vBox.prefHeightProperty());

                                }
                                else
                                {
                                    content=transfor(arg0.getContent());
                                    content.setMaxWidth(400);

                                    content.setTextAlignment(TextAlignment.LEFT);
                                    content.setPadding(new Insets(20,20,20,20));
                                    BackgroundFill backgroundFill=new BackgroundFill(Color.LIGHTPINK,CornerRadii.EMPTY,Insets.EMPTY);
                                    Background bg=new Background(backgroundFill);
                                    content.setBackground(bg);

                                    VBox vBox=new VBox(10);

                                    HBox hBox=new HBox(10);
                                    hBox.getChildren().addAll(imageView,content);

                                    HBox.setHgrow(imageView, Priority.ALWAYS);
                                    HBox.setHgrow(content,Priority.ALWAYS);
                                    hBox.setAlignment(Pos.TOP_LEFT);

                                    vBox.setAlignment(Pos.TOP_CENTER);
                                    vBox.getChildren().addAll(date,hBox);

                                    this.setGraphic(vBox);

                                    prefHeightProperty().bind(vBox.prefHeightProperty());
                                }

                                imageView.setOnMouseClicked((MouseEvent event)->
                                {
                                    if(friendmap.get(arg0.getSender()).getEmailNumber()!=null)
                                    {
                                        PrivateInformation privateInformation=Main.AllContronller.getPrivateInformationControllerById(arg0.getSender());
                                        if(privateInformation!=null) return ;
                                        Stage stage=new Stage();
                                        File file=new File("E:\\JDK\\QQClient\\nox\\src\\fxml\\PrivateInformation.fxml");
                                        URL location= null;
                                        try {
                                            location = file.toURI().toURL();
                                        } catch (MalformedURLException e) {
                                            throw new RuntimeException(e);
                                        }
                                        FXMLLoader fxmlLoader=new FXMLLoader();
                                        fxmlLoader.setLocation(location);
                                        Parent root= null;
                                        try {
                                            root = fxmlLoader.load();
                                        } catch (IOException e) {
                                            throw new RuntimeException(e);
                                        }
                                        stage.setTitle("查看他人信息");
                                        stage.setResizable(false);
                                        stage.setScene(new Scene(root,400,600));
                                        stage.show();
                                        privateInformation=fxmlLoader.getController();
                                        Main.AllContronller.AddPrivateInformationController(arg0.getSender(),null);
                                        getInformation(data.getIdentity(),friendmap.get(arg0.getSender()),privateInformation);
                                    }
                                    else
                                    {
                                        System.out.println("需要这个好友的信息");
                                        //说明还没有这个人的信息，需要向服务器请求
                                        event massage=new event();
                                        massage.setType(MassageType.Request_Get_Friend_Information_From_Group);
                                        GroupFriendData groupFriendData=friendmap.get(arg0.getSender());
                                        groupFriendData.setGroup_id(data.getGroup_id());
                                        massage.setT(groupFriendData);

                                        try {
                                            new SendMassage().sendMassage(massage);
                                        } catch (IOException e) {
                                            throw new RuntimeException(e);
                                        }
                                    }
                                });
                            }
                        }
                        else
                        {
                        //    setPrefHeight(0);
                        }
                    }
                };
                return list;
            }
        });

    }


    public void setMassage(ArrayList<MassageData> arraylist)
    {
        MassageOblist=MassageList.getItems();
        MassageOblist.clear();
        MassageOblist=MassageList.getItems();
        MassageOblist.addAll(arraylist);
        MassageOblist.add(0,null);

        MassageList.scrollTo(MassageOblist.size()-1);

        System.out.println("此时的消息为"+MassageOblist.size());

    //    MassageList.setSelectionModel(null);
        System.out.println("添加消息数组成功");

        MassageList.setCellFactory(new Callback<ListView<MassageData>, ListCell<MassageData>>() {
            @Override
            public ListCell<MassageData> call(ListView<MassageData> param) {
                ListCell<MassageData> list=new ListCell<MassageData>(){
                    @Override
                    protected void updateItem(MassageData arg0, boolean arg1) {
                        super.updateItem(arg0, arg1);
                        if(getIndex()==0)
                        {
                            setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
                            HBox hBox=new HBox(30);
                            Button getmore=new Button("获得更多消息");
                            hBox.getChildren().add(getmore);
                            hBox.setAlignment(Pos.TOP_CENTER);
                            this.setGraphic(hBox);

                            getmore.setOnMouseClicked((MouseEvent event)->
                            {
                                //点击事件，是向服务器发送更多消息的请求
                                System.out.println(MassageOblist.size()-1);
                                if(MassageOblist.size()<=1)
                                {
                                    Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                    alert.setTitle("错误");
                                    alert.setHeaderText(null);
                                    alert.setContentText("没有更多消息了!");
                                    alert.showAndWait();
                                }
                                else
                                {
                                    Data.event massage=new event();
                                    massage.setType(MassageType.Request_Chat_Massage);
                                    Timestamp timestamp=new Timestamp(System.currentTimeMillis());

                                    MassageData massageData=new MassageData(data.getId(),data.getGroup_id(),timestamp,"");
                                    massageData.setSum(MassageOblist.size()-1);
                                    massage.setT(massageData);
                                    try {
                                        new SendMassage().sendMassage(massage);
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                }
                            });
                        }
                        else if(arg1==false){

                            setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
                            HBox hbox=new HBox(30);
                            hbox.setAlignment(Pos.BASELINE_LEFT);//对齐显示

                            //需要头像，消息，以及日期
                            if(arg0.getSender().equals(data.getId()))
                            {
                                //代表是自己发的
                                Image image=myavatar;
                                ImageView imageView=new ImageView(image);
                                imageView.setFitWidth(50);
                                imageView.setFitHeight(50);
                                Circle circle=new Circle(25,25,25);
                                imageView.setClip(circle);

                                Timestamp timestamp=arg0.getTimestamp();
                                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm");
                                String formatted=sdf.format(timestamp);
                                Label date=new Label(formatted);

                                TextFlow content=new TextFlow();
                                if(arg0.getIs_file()==1)
                                {
                                    //说明这是文件
                                    Image fileimage=new Image("file:"+"E:\\JDK\\QQClient\\nox\\src\\img\\img_1.png");
                                    ImageView fileimageview=new ImageView(fileimage);
                                    fileimageview.setFitWidth(60);
                                    fileimageview.setFitHeight(60);

                                    Label filename=new Label(arg0.getFile_name());
                                    filename.setFont(new Font(10));
                                    VBox vBox=new VBox(10);
                                    vBox.setAlignment(Pos.TOP_RIGHT);
                                    vBox.getChildren().addAll(fileimageview,filename);

                                    HBox hBox=new HBox(20);
                                    hBox.getChildren().addAll(vBox,imageView);
                                    HBox.setHgrow(imageView,Priority.ALWAYS);
                                    HBox.setHgrow(vBox,Priority.ALWAYS);
                                    hBox.setAlignment(Pos.TOP_RIGHT);

                                    VBox vBox1=new VBox();
                                    vBox1.setAlignment(Pos.TOP_CENTER);
                                    vBox1.getChildren().addAll(date,hBox);

                                    this.setGraphic(vBox1);
                                    prefHeightProperty().bind(hBox.prefHeightProperty());

                                    hBox.setOnMouseClicked((MouseEvent event)->
                                    {
                                        //先判断本地是否已经有这个文件
                                        File newfile=new File("F:\\qqclientfile"+"\\"+arg0.getFile_name());
                                        if(newfile.exists())
                                        {
                                            //打开这个文件
                                            Desktop desktop=Desktop.getDesktop();
                                            if(desktop.isSupported(Desktop.Action.OPEN))
                                            {
                                                try {
                                                    desktop.open(newfile);
                                                } catch (IOException e) {
                                                    throw new RuntimeException(e);
                                                }
                                            }
                                            else
                                            {
                                                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                                alert.setTitle("错误");
                                                alert.setHeaderText(null);
                                                alert.setContentText("不支持打开此文件类型，请到"+newfile.getAbsolutePath()+"中查看!");
                                                alert.showAndWait();
                                            }
                                        }
                                        else
                                        {
                                            //没有就申请下载
                                            //向服务器发送请求，因为已经知道了该文件的id，发送一个请求id的代码

                                            event massage=new event();
                                            MassageData data=new MassageData();
//                                        data.setSender(arg0.getSender());
//                                        data.setReceiver(arg0.getReceiver());
                                            data.setFile_name(arg0.getFile_name());
                                            data.setFile_id(arg0.getFile_id());
                                            massage.setType(MassageType.Request_Get_File);
                                            massage.setT(data);
                                            try {
                                                new SendMassage().sendMassage(massage);
                                            } catch (IOException e) {
                                                throw new RuntimeException(e);
                                            }
                                        }

                                    });

                                }
                                else
                                {
                                    content=transfor(arg0.getContent());
                                    content.setMaxWidth(400);

                                    content.setTextAlignment(TextAlignment.RIGHT);
                                    content.setPadding(new Insets(20,20,20,20));
                                    BackgroundFill backgroundFill=new BackgroundFill(Color.LIGHTBLUE,CornerRadii.EMPTY,Insets.EMPTY);
                                    Background bg=new Background(backgroundFill);
                                    content.setBackground(bg);
                                    VBox vBox=new VBox(10);

                                    HBox hBox=new HBox(10);
                                    hBox.getChildren().addAll(content,imageView);

                                    HBox.setHgrow(imageView, Priority.ALWAYS);
                                    HBox.setHgrow(content,Priority.ALWAYS);
                                    hBox.setAlignment(Pos.TOP_RIGHT);

                                    vBox.setAlignment(Pos.TOP_CENTER);
                                    vBox.getChildren().addAll(date,hBox);
                                    this.setGraphic(vBox);
                                    prefHeightProperty().bind(vBox.prefHeightProperty());
                                }

                                imageView.setOnMouseClicked((MouseEvent event)->{
                                    //加载自己的个人信息
                                    PrivateInformation privateInformation=Main.AllContronller.getPrivateInformationController();
                                    if(privateInformation!=null) return;

                                    Stage stage=new Stage();
                                    File file=new File("E:\\JDK\\QQClient\\nox\\src\\fxml\\PrivateInformation.fxml");
                                    URL location= null;
                                    try {
                                        location = file.toURI().toURL();
                                    } catch (MalformedURLException e) {
                                        throw new RuntimeException(e);
                                    }
                                    FXMLLoader fxmlLoader=new FXMLLoader();
                                    fxmlLoader.setLocation(location);
                                    Parent root= null;
                                    try {
                                        root = fxmlLoader.load();
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                    stage.setTitle("个人信息修改");
                                    stage.setResizable(false);
                                    stage.setScene(new Scene(root,400,600));
                                    stage.show();
                                    privateInformation=fxmlLoader.getController();
                                    Main.AllContronller.setPrivateInformationController(privateInformation);
                                    ChatMain chatMain= Main.getAllContronller().getChatMainController();
//
                                    PrivateInformationData mydata=chatMain.getMydata();
                                    privateInformation.changeInformation(mydata);

                                    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                                        @Override
                                        public void handle(WindowEvent event) {
                                            stage.close();
                                            Main.AllContronller.setPrivateInformationController(null);
                                            //    System.out.print("监听到窗口关闭");
                                        }
                                    });
                                });
                            }
                            else
                            {
                                Image image=null;
                                if(friendmap.get(arg0.getSender())==null)
                                {
                                    image=new Image("file:"+"E:\\JDK\\QQClient\\nox\\src\\img\\avatar\\img.png");
                                }
                                else
                                {
                                    byte[] bytes=friendmap.get(arg0.getSender()).getAvatar();
                                    image=new Image(new ByteArrayInputStream(bytes));
                                }

                                ImageView imageView=new ImageView(image);
                                imageView.setFitWidth(50);
                                imageView.setFitHeight(50);
                                Circle circle=new Circle(25,25,25);
                                imageView.setClip(circle);

                                Timestamp timestamp=arg0.getTimestamp();
                                SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm");
                                String formatted=sdf.format(timestamp);
                                Label date=new Label(formatted);

                                TextFlow content=new TextFlow();
                                if(arg0.getIs_file()==1)
                                {
                                    //说明这是文件
                                    Image fileimage=new Image("file:"+"E:\\JDK\\QQClient\\nox\\src\\img\\img_1.png");
                                    ImageView fileimageview=new ImageView(fileimage);
                                    fileimageview.setFitWidth(60);
                                    fileimageview.setFitHeight(60);

                                    Label filename=new Label(arg0.getFile_name());
                                    filename.setFont(new Font(10));
                                    VBox vBox=new VBox(10);
                                    vBox.setAlignment(Pos.TOP_LEFT);
                                    vBox.getChildren().addAll(date,fileimageview,filename);

                                    HBox hBox=new HBox(20);
                                    hBox.getChildren().addAll(imageView,vBox);
                                    HBox.setHgrow(imageView,Priority.ALWAYS);
                                    HBox.setHgrow(vBox,Priority.ALWAYS);
                                    hBox.setAlignment(Pos.TOP_LEFT);

                                    VBox vBox1=new VBox();
                                    vBox1.setAlignment(Pos.TOP_CENTER);
                                    vBox1.getChildren().addAll(date,hBox);

                                    this.setGraphic(vBox1);
                                    prefHeightProperty().bind(hBox.prefHeightProperty());

                                    hBox.setOnMouseClicked((MouseEvent event)->
                                    {
                                        //先判断本地是否已经有这个文件
                                        File newfile=new File("F:\\qqclientfile"+"\\"+arg0.getFile_name());
                                        if(newfile.exists())
                                        {
                                            //打开这个文件
                                            Desktop desktop=Desktop.getDesktop();
                                            if(desktop.isSupported(Desktop.Action.OPEN))
                                            {
                                                try {
                                                    desktop.open(newfile);
                                                } catch (IOException e) {
                                                    throw new RuntimeException(e);
                                                }
                                            }
                                            else
                                            {
                                                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                                                alert.setTitle("错误");
                                                alert.setHeaderText(null);
                                                alert.setContentText("不支持打开此文件类型，请到"+newfile.getAbsolutePath()+"中查看!");
                                                alert.showAndWait();
                                            }
                                        }
                                        else
                                        {
                                            //没有就申请下载
                                            //向服务器发送请求，因为已经知道了该文件的id，发送一个请求id的代码

                                            event massage=new event();
                                            MassageData data=new MassageData();
//                                        data.setSender(arg0.getSender());
//                                        data.setReceiver(arg0.getReceiver());
                                            data.setFile_name(arg0.getFile_name());
                                            data.setFile_id(arg0.getFile_id());
                                            massage.setType(MassageType.Request_Get_File);
                                            massage.setT(data);
                                            try {
                                                new SendMassage().sendMassage(massage);
                                            } catch (IOException e) {
                                                throw new RuntimeException(e);
                                            }
                                        }

                                    });
                                    prefHeightProperty().bind(vBox.prefHeightProperty());

                                }
                                else
                                {
                                    content=transfor(arg0.getContent());
                                    content.setMaxWidth(400);

                                    content.setTextAlignment(TextAlignment.LEFT);
                                    content.setPadding(new Insets(20,20,20,20));
                                    BackgroundFill backgroundFill=new BackgroundFill(Color.LIGHTPINK,CornerRadii.EMPTY,Insets.EMPTY);
                                    Background bg=new Background(backgroundFill);
                                    content.setBackground(bg);

                                    VBox vBox=new VBox(10);

                                    HBox hBox=new HBox(10);
                                    hBox.getChildren().addAll(imageView,content);

                                    HBox.setHgrow(imageView, Priority.ALWAYS);
                                    HBox.setHgrow(content,Priority.ALWAYS);
                                    hBox.setAlignment(Pos.TOP_LEFT);

                                    vBox.setAlignment(Pos.TOP_CENTER);
                                    vBox.getChildren().addAll(date,hBox);

                                    this.setGraphic(vBox);

                                    prefHeightProperty().bind(vBox.prefHeightProperty());
                                }

                                imageView.setOnMouseClicked((MouseEvent event)->
                                {
                                    if(friendmap.get(arg0.getSender())==null) return ;
                                    if(friendmap.get(arg0.getSender()).getEmailNumber()!=null)
                                    {
                                        PrivateInformation privateInformation=Main.AllContronller.getPrivateInformationControllerById(arg0.getSender());
                                        if(privateInformation!=null) return;

                                        Stage stage=new Stage();
                                        File file=new File("E:\\JDK\\QQClient\\nox\\src\\fxml\\PrivateInformation.fxml");
                                        URL location= null;
                                        try {
                                            location = file.toURI().toURL();
                                        } catch (MalformedURLException e) {
                                            throw new RuntimeException(e);
                                        }
                                        FXMLLoader fxmlLoader=new FXMLLoader();
                                        fxmlLoader.setLocation(location);
                                        Parent root= null;
                                        try {
                                            root = fxmlLoader.load();
                                        } catch (IOException e) {
                                            throw new RuntimeException(e);
                                        }
                                        stage.setTitle("查看他人信息");
                                        stage.setResizable(false);
                                        stage.setScene(new Scene(root,400,600));
                                        stage.show();
                                        privateInformation=fxmlLoader.getController();
                                        Main.AllContronller.AddPrivateInformationController(arg0.getSender(),privateInformation);
                                        getInformation(data.getIdentity(),friendmap.get(arg0.getSender()),privateInformation);
                                    }
                                    else
                                    {
                                        System.out.println("需要这个好友的信息");
                                        //说明还没有这个人的信息，需要向服务器请求
                                        event massage=new event();
                                        massage.setType(MassageType.Request_Get_Friend_Information_From_Group);
                                        GroupFriendData groupFriendData=friendmap.get(arg0.getSender());
                                        groupFriendData.setGroup_id(data.getGroup_id());
                                        massage.setT(groupFriendData);

                                        try {
                                            new SendMassage().sendMassage(massage);
                                        } catch (IOException e) {
                                            throw new RuntimeException(e);
                                        }
                                    }
                                });
                            }
                        }
                        else
                        {
                            //    setPrefHeight(0);
                        }
                    }
                };
                return list;
            }
        });

        System.out.println("在显示了");
    }
    private static final String regex="\\[\\{(1[0-8][0-7]|[1-9][0-9]|[1-9])(dynamic|static)}]";
    private static final Pattern PATTERN=Pattern.compile(regex);
    public TextFlow transfor(String massage)
    {

        TextFlow content=new TextFlow();
        content.setPadding(new Insets(10));
        Matcher matcher= PATTERN.matcher(massage);
        String res=new String();
        int index=0;
        while(matcher.find())
        {
            String match=matcher.group();
            if(matcher.start()>index)
            {
                Text text=new Text(massage.substring(index,matcher.start()));
                //    text.setFont(new Font("Arial",30));
                content.getChildren().add(text);
            }

            Image image=null;
            ImageView imageView=new ImageView();
            System.out.println(match.substring(0,match.length()));
            if(match.substring(0,match.length()).contains("dynamic"))
            {
                image=new Image("file:"+"E:\\JDK\\QQClient\\nox\\src\\emoji\\dynamic\\"+match.substring(2,match.length()-9)+".gif");
                imageView.setImage(image);
            }
            else if(match.substring(0,match.length()).contains("static"))
            {
                image=new Image("file:"+"E:\\JDK\\QQClient\\nox\\src\\emoji\\static\\"+match.substring(2,match.length()-8)+".png");
                imageView.setImage(image);
            }
            imageView.setFitWidth(20);
            imageView.setPreserveRatio(true);
            imageView.setFitHeight(20);
            content.getChildren().add(imageView);
            index=matcher.end();
        }
        if(index<massage.length())
        {
            Text text=new Text(massage.substring(index));
            content.getChildren().add(text);
        }

        return content;
    }
    @FXML
    private ListView<GroupFriendData> groupfriendlist;

    private ObservableList<GroupFriendData> friendoblist;

    private ArrayList<GroupFriendData> friendArryList;

    public ArrayList<GroupFriendData> getFriendArryList() {
        return friendArryList;
    }

    public void delfriend(GroupFriendData groupFriendData)
    {
        friendmap.remove(groupFriendData.getId());
        for (int i = 0; i < friendArryList.size(); i++) {
            if(friendArryList.get(i).getId().equals(groupFriendData.getId()))
            {
                friendArryList.remove(i);
                break;
            }
        }
        setAllFriend(friendArryList);
    }

    public void setAllFriend(ArrayList<GroupFriendData> arry)
    {
        friendoblist= FXCollections.observableArrayList();
        groupfriendlist.setItems(friendoblist);

        friendoblist.setAll(arry);
        groupfriendlist.refresh();

        friendArryList=arry;
        System.out.println(friendArryList.size());

        friendmap.clear();
        for (int i = 0; i < arry.size(); i++) {
            friendmap.put(arry.get(i).getId(),arry.get(i));
            System.out.println(friendArryList.get(i));
        }
        System.out.println("设置好友成功");

        groupfriendlist.setCellFactory(new Callback<ListView<GroupFriendData>, ListCell<GroupFriendData>>() {
            @Override
            public ListCell<GroupFriendData> call(ListView<GroupFriendData> param) {
                ListCell<GroupFriendData> list=new ListCell<GroupFriendData>(){
                    @Override
                    protected void updateItem(GroupFriendData arg0, boolean arg1) {
                        super.updateItem(arg0, arg1);
                        if(arg1==false) {
                            //需要有身份标签，和昵称，头像
                            setPrefHeight(60);
                            Image image = null;
                            Label identity = null;
                            Label Nickname = null;
                            HBox hbox=new HBox(10);
                            setBackground(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY)));
                            hbox.setAlignment(Pos.BASELINE_LEFT);
                            if(arg0.getIdentity()==1)
                            {
                                //群主
                                image=new Image(new ByteArrayInputStream(arg0.getAvatar()));
                                identity=new Label("群主");
                                identity.setFont(new Font(15));
                                identity.setTextFill(Color.RED);
                                Nickname=new Label(arg0.getUserNickName());

                            }
                            else if(arg0.getIdentity()==2)
                            {
                                //管理员
                                image=new Image(new ByteArrayInputStream(arg0.getAvatar()));
                                identity=new Label("管理员");
                                identity.setFont(new Font(15));
                                identity.setTextFill(Color.ORANGE);
                                Nickname=new Label(arg0.getUserNickName());
                            }
                            else if(arg0.getIdentity()==3)
                            {
                                //普通人
                                image=new Image(new ByteArrayInputStream(arg0.getAvatar()));
                                identity=new Label("");
                                Nickname=new Label(arg0.getUserNickName());
                            }
                            else if(arg0.getIdentity()==0)
                            {
                                //需要验证好友进去的
                                if(data.getIdentity()!=3)
                                {
                                    System.out.println("这个是需要验证的好友"+arg0.getId());
                                    image=new Image(new ByteArrayInputStream(arg0.getAvatar()));
                                    identity=new Label("请求加入群聊");
                                    identity.setFont(new Font(15));
                                    identity.setTextFill(Color.YELLOW);
                                    Nickname=new Label(arg0.getUserNickName());

                                }
                                else
                                {
//                                    setPrefHeight(0);
                                    return;
                                }
                            }
                            ImageView imageView=new ImageView(image);
                            imageView.setFitWidth(50);
                            imageView.setFitHeight(50);

                            Circle circle=new Circle(25,25,25);
                            imageView.setClip(circle);

                            hbox.getChildren().addAll(imageView,Nickname,identity);
                            this.setGraphic(hbox);

                            //设置点击事件
                            hbox.setOnMouseClicked((MouseEvent event)->
                            {
                                //好友列表可以查看消息,如果点击的是自己的信息
                                if(data.getId().equals(arg0.getId()))
                                {
                                    //说明是自己的
                                    PrivateInformation privateInformation=Main.AllContronller.getPrivateInformationController();
                                    if(privateInformation!=null) return;

                                    Stage stage=new Stage();
                                    File file=new File("E:\\JDK\\QQClient\\nox\\src\\fxml\\PrivateInformation.fxml");
                                    URL location= null;
                                    try {
                                        location = file.toURI().toURL();
                                    } catch (MalformedURLException e) {
                                        throw new RuntimeException(e);
                                    }
                                    FXMLLoader fxmlLoader=new FXMLLoader();
                                    fxmlLoader.setLocation(location);
                                    Parent root= null;
                                    try {
                                        root = fxmlLoader.load();
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                    stage.setTitle("个人信息修改");
                                    stage.setResizable(false);
                                    stage.setScene(new Scene(root,400,600));
                                    stage.show();
                                    privateInformation=fxmlLoader.getController();
                                    Main.AllContronller.setPrivateInformationController(privateInformation);
                                    ChatMain chatMain= Main.getAllContronller().getChatMainController();
//
                                    PrivateInformationData mydata=chatMain.getMydata();
                                    privateInformation.changeInformation(mydata);

                                    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                                        @Override
                                        public void handle(WindowEvent event) {
                                            stage.close();
                                            Main.AllContronller.setPrivateInformationController(null);
                                            //    System.out.print("监听到窗口关闭");
                                        }
                                    });
                                }
                                else if(arg0.getIdentity()!=0)
                                {
                                    //这里还需要判断一下是否已经打开了一个
                                    PrivateInformation privateInformation=Main.AllContronller.getPrivateInformationControllerById(arg0.getId());
                                    if(privateInformation!=null) return ;

                                    if(friendmap.get(arg0.getId()).getEmailNumber()!=null)
                                    {
                                        privateInformation=Main.AllContronller.getPrivateInformationControllerById(arg0.getId());
                                        if(privateInformation!=null)  return;
                                        Stage stage=new Stage();
                                        File file=new File("E:\\JDK\\QQClient\\nox\\src\\fxml\\PrivateInformation.fxml");
                                        URL location= null;
                                        try {
                                            location = file.toURI().toURL();
                                        } catch (MalformedURLException e) {
                                            throw new RuntimeException(e);
                                        }
                                        FXMLLoader fxmlLoader=new FXMLLoader();
                                        fxmlLoader.setLocation(location);
                                        Parent root= null;
                                        try {
                                            root = fxmlLoader.load();
                                        } catch (IOException e) {
                                            throw new RuntimeException(e);
                                        }
                                        stage.setTitle("查看他人信息");
                                        stage.setResizable(false);
                                        stage.setScene(new Scene(root,400,600));
                                        stage.show();
                                        privateInformation=fxmlLoader.getController();
                                        getInformation(data.getIdentity(),friendmap.get(arg0.getId()),privateInformation);

                                        Main.AllContronller.AddPrivateInformationController(arg0.getId(),privateInformation);

                                        stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                                            @Override
                                            public void handle(WindowEvent event) {
                                                stage.close();
                                                Main.AllContronller.AddPrivateInformationController(arg0.getId(),null);
                                                //    System.out.print("监听到窗口关闭");
                                            }
                                        });
                                    }
                                    else
                                    {
                                        System.out.println("需要这个好友的信息");
                                        //说明还没有这个人的信息，需要向服务器请求
                                        event massage=new event();
                                        massage.setType(MassageType.Request_Get_Friend_Information_From_Group);
                                        GroupFriendData groupFriendData=friendmap.get(arg0.getId());
                                        groupFriendData.setGroup_id(data.getGroup_id());
                                        massage.setT(groupFriendData);

                                        try {
                                            new SendMassage().sendMassage(massage);
                                        } catch (IOException e) {
                                            throw new RuntimeException(e);
                                        }
                                    }
                                 //   getInformation(data.getIdentity(),friendmap.get(arg0.getId()),privateInformation);
                                }
                                else if(data.getIdentity()!=3&&arg0.getIdentity()==0)
                                {
                                    VerifyFriends verifyFriends=Main.AllContronller.getVerifyFriendStagById(arg0.getId());
                                    if(verifyFriends!=null) return ;

                                    //这是需要验证好友进群的消息
                                    Stage stage=new Stage();
                                    File file=new File("E:\\JDK\\QQClient\\nox\\src\\fxml\\verify Friends.fxml");
                                    URL location= null;
                                    try {
                                        location = file.toURI().toURL();
                                    } catch (MalformedURLException e) {
                                        throw new RuntimeException(e);
                                    }
                                    FXMLLoader fxmlLoader=new FXMLLoader();
                                    fxmlLoader.setLocation(location);
                                    Parent root= null;
                                    try {
                                        root = fxmlLoader.load();
                                    } catch (IOException e) {
                                        throw new RuntimeException(e);
                                    }
                                    stage.setTitle("进群请求");
                                    stage.setResizable(false);
                                    stage.setScene(new Scene(root,400,400));
                                    stage.show();
                                    verifyFriends=fxmlLoader.getController();
                                    verifyFriends.setGroupVerify(arg0,data);

                                    Main.AllContronller.AddVerifyFriendStage(arg0.getId(),verifyFriends);

                                    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
                                        @Override
                                        public void handle(WindowEvent event) {
                                            Main.AllContronller.AddVerifyFriendStage(arg0.getId(),null);
                                            stage.close();
                                        }
                                    });
                                }
                            });
                        }
                        else
                        {
                            setPrefHeight(0);
                        }

                    }

                };
                return list;
            }
        });
        groupfriendlist.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                if(event.getButton().equals(MouseButton.PRIMARY))
                {
                    if(event.getClickCount()==1)
                    {
                        groupfriendlist.getSelectionModel().clearSelection();
                    }
                }
            }
        });

        //设置好友

    }

    public void setInitGroup()
    {
        group_id.setText("群聊id为"+data.getGroup_id());
        group_name.setText(data.getGroup_name());

        if(data.getGroup_avatar()!=null)
        {
            group_avatar.setImage(new Image(new ByteArrayInputStream(data.getGroup_avatar())));
        }

        group_saying.setText(data.getGroup_saying());
        group_saying.setWrapText(true);

    }


    public void setGroupOwner(GroupData groupData)
    {
        //设置群主的界面
        //设置群聊右边的显示
        System.out.println("此时是群主");
        delete_group.setVisible(true);
        delete_group.setDisable(false);

        group_avatar.setDisable(false);
        group_name.setEditable(true);
        group_saying.setEditable(true);

        submitButton.setVisible(true);
        submitButton.setDisable(false);

    }

    public void setAdmin(GroupData groupData)
    {
        //管理员的界面
        System.out.println("此时是管理员");
        delete_group.setVisible(false);
        delete_group.setDisable(true);

        group_avatar.setDisable(false);
        group_name.setEditable(true);
        group_saying.setEditable(true);

        submitButton.setVisible(true);
        submitButton.setDisable(false);
    }

    public void setPeople(GroupData groupData)
    {
        //普通人的界面
        System.out.println("此时是普通人");
        delete_group.setVisible(false);
        delete_group.setDisable(true);

        group_avatar.setDisable(true);
        group_name.setEditable(false);
        group_saying.setEditable(false);

        submitButton.setVisible(false);
        submitButton.setDisable(true);

    }
    @FXML
    void SendMassageAction(ActionEvent event) throws IOException {
        if(GetMassage.getText().equals(""))
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("错误");
            alert.setHeaderText(null);
            alert.setContentText("消息为空!");
            alert.showAndWait();
        }
        else
        {
            Data.event massage=new event();
            massage.setType(MassageType.Send_Massage_To_Group);
            Timestamp timestamp=new Timestamp(System.currentTimeMillis());

            MassageData newmassage=new MassageData(data.getId(),data.getGroup_id(),timestamp,GetMassage.getText());

             GroupMassageData groupMassageData=new GroupMassageData();
             groupMassageData.setMassageData(newmassage);
             groupMassageData.setArrayList(friendArryList);

             massage.setT(groupMassageData);

            new SendMassage().sendMassage(massage);
            GetMassage.clear();
        }
    }


    @FXML
    void putFriend(ActionEvent event)
    {
        InviteOtherToGroup inviteOtherToGroup=Main.AllContronller.getInviteOtherToGroupControllerById(data.getGroup_id());
        if(inviteOtherToGroup!=null) return ;
        //邀请好友
        Stage stage=new Stage();
        File file=new File("E:\\JDK\\QQClient\\nox\\src\\fxml\\InviteOtherToGroup.fxml");
        URL location= null;
        try {
            location = file.toURI().toURL();
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        FXMLLoader fxmlLoader=new FXMLLoader();
        fxmlLoader.setLocation(location);
        Parent root= null;
        try {
            root = fxmlLoader.load();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        stage.setTitle("邀请好友");
        stage.setResizable(false);
        stage.setScene(new Scene(root,500,400));
        stage.show();


        inviteOtherToGroup=fxmlLoader.getController();
        inviteOtherToGroup.setGroupData(data);
        ChatMain chatMain=Main.AllContronller.getChatMainController();
        inviteOtherToGroup.setStage(chatMain.getPrivateInformationArry(),friendmap);

        Main.AllContronller.AddInviteToOtherGroupController(data.getGroup_id(),inviteOtherToGroup);
        System.out.println(data.getGroup_id()+"invite控制类已经进去了哦");

        InviteOtherToGroup finalInviteOtherToGroup = inviteOtherToGroup;
        stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent event) {
                System.out.println(data.getGroup_id()+"invite窗口已经关闭");
                    Main.AllContronller.RemoveInviteToOtherController(data.getGroup_id());
                //    System.out.print("监听到窗口关闭");
            }
        });
    }

    @FXML
    void outGroup(ActionEvent event) throws IOException {
        //退出群聊
        event massage=new event();
        //判断一下是不是群主
        if(data.getIdentity()==1)
        {
            //是群主，需要判断是否解散群聊还是移交群主
            Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
            alert.setTitle("选择");
            alert.setHeaderText("您现在是群主的身份，你点击此按钮需要做出选择");
            alert.setContentText("如果您希望退出群聊之后，该群聊不复存在，请点击解散该群，否则点击移交群主，或者如果您不小心误点了，请选择取消按钮");

            ButtonType buttonTypeOne = new ButtonType("移交群主");
            ButtonType buttonTypeTwo = new ButtonType("解散该群");
            ButtonType buttonTypeCancel = new ButtonType("取消", ButtonBar.ButtonData.CANCEL_CLOSE);

            alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeTwo, buttonTypeCancel);

            Optional<ButtonType> result = alert.showAndWait();
            if (result.get() == buttonTypeOne){
                //移交群主
                alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("提示");
                alert.setHeaderText(null);
                alert.setContentText("请先移交群主，再点击退出群聊，谢谢!");
                alert.showAndWait();
            } else if (result.get() == buttonTypeTwo) {
                //解散该群
                deleteGroup(event);
            } else
            {

            }

        }
        else
        {
            //如果不是群主
            massage.setType(MassageType.Request_Delete_Group_People);

            GroupOperationData groupOperationData=new GroupOperationData();
            GroupFriendData groupFriendData=new GroupFriendData();
            groupFriendData.setId(data.getId());
            groupFriendData.setGroup_id(data.getGroup_id());
            groupFriendData.setIdentity(data.getIdentity());
            groupOperationData.setReceiver(groupFriendData);
        //    groupOperationData.setReceiver(groupFriendData);

            groupOperationData.setFriendlist(data.getGroup_friend_list());
            massage.setT(groupOperationData);

            new SendMassage().sendMassage(massage);

            CloseStage();
        }
    }

    @FXML
    void initialize() {
        GetMassage.setPrefRowCount(5);
        GetMassage.setPrefRowCount(50);
        GetMassage.setWrapText(true);

        MassageOblist=MassageList.getItems();
        MassageOblist.clear();
        MassageOblist=MassageList.getItems();

        SeeEmoji.setHbarPolicy(ScrollPane.ScrollBarPolicy.NEVER);

        SeeEmoji.setVisible(false);
        SeeEmoji.setDisable(true);
        for (int i = 0; i < 188; i++) {
            String path = "E:\\JDK\\QQClient\\nox\\src\\emoji\\dynamic\\" + (i + 1) + ".gif";
            Image image = new Image("file:" + path);
            ImageView imageView = new ImageView();
            imageView.setImage(image);
            imageView.setPreserveRatio(true);
            imageView.setFitWidth(20);
            imageView.setFitWidth(20);
            dynamicEmoji.getChildren().add(imageView);
            String finalPath = path;
            int finalI2 = i;
            imageView.setOnMouseClicked((MouseEvent event) ->
            {
                int position = GetMassage.getCaretPosition();
                GetMassage.replaceText(position, position, "[{" + (finalI2 + 1) + "dynamic" + "}]");
                System.out.println(finalPath);
            });

            path = "E:\\JDK\\QQClient\\nox\\src\\emoji\\static\\" + (i + 1) + ".png";
            image = new Image("file:" + path);
            imageView = new ImageView();
            imageView.setImage(image);
            imageView.setPreserveRatio(true);
            imageView.setFitWidth(20);
            imageView.setFitWidth(20);
            nodynamicEmoji.getChildren().add(imageView);

            String finalPath1 = path;
            int finalI1 = i;
            imageView.setOnMouseClicked((MouseEvent event) ->
            {
                int position = GetMassage.getCaretPosition();
                GetMassage.replaceText(position, position, "[{" + (finalI1 + 1) + "static" + "}]");
                System.out.println(finalPath1);
            });
        }
        assert GetMassage != null : "fx:id=\"GetMassage\" was not injected: check your FXML file 'group_Stage.fxml'.";
        assert emoji != null : "fx:id=\"emoji\" was not injected: check your FXML file 'group_Stage.fxml'.";
        assert group_name != null : "fx:id=\"group_name\" was not injected: check your FXML file 'group_Stage.fxml'.";
        assert staticScroll != null : "fx:id=\"staticScroll\" was not injected: check your FXML file 'group_Stage.fxml'.";
        assert put_friend != null : "fx:id=\"put_friend\" was not injected: check your FXML file 'group_Stage.fxml'.";
        assert out_group != null : "fx:id=\"out_group\" was not injected: check your FXML file 'group_Stage.fxml'.";
        assert SendMassage != null : "fx:id=\"SendMassage\" was not injected: check your FXML file 'group_Stage.fxml'.";
        assert group_avatar != null : "fx:id=\"group_avatar\" was not injected: check your FXML file 'group_Stage.fxml'.";
        assert dynamicEmoji != null : "fx:id=\"dynamicEmoji\" was not injected: check your FXML file 'group_Stage.fxml'.";
        assert nodynamic != null : "fx:id=\"nodynamic\" was not injected: check your FXML file 'group_Stage.fxml'.";
        assert file != null : "fx:id=\"file\" was not injected: check your FXML file 'group_Stage.fxml'.";
        assert GetMoreMassage != null : "fx:id=\"GetMoreMassage\" was not injected: check your FXML file 'group_Stage.fxml'.";
        assert group_id != null : "fx:id=\"group_id\" was not injected: check your FXML file 'group_Stage.fxml'.";
        assert dynamic != null : "fx:id=\"dynamic\" was not injected: check your FXML file 'group_Stage.fxml'.";
        assert nodynamicEmoji != null : "fx:id=\"nodynamicEmoji\" was not injected: check your FXML file 'group_Stage.fxml'.";
        assert SeeEmoji != null : "fx:id=\"SeeEmoji\" was not injected: check your FXML file 'group_Stage.fxml'.";
        assert dynamicScroll != null : "fx:id=\"dynamicScroll\" was not injected: check your FXML file 'group_Stage.fxml'.";
        assert MassageList != null : "fx:id=\"MassageList\" was not injected: check your FXML file 'group_Stage.fxml'.";
    }

    public void ChangeGroupInformation(ActionEvent actionEvent) throws IOException {
        //点击修改了群资料
        GroupData groupData=new GroupData();
        String name=group_name.getText();
        String saying=group_saying.getText();
        if(file!=null)
        {
            //说明已经修改过了
            FileInputStream fileInputStream=new FileInputStream(file);
            byte[] t=new byte[(int) file.length()];
            fileInputStream.read(t);
            groupData.setGroup_avatar(t);

            String filename=null;
            filename=file.getName();
            int dotIndex=filename.lastIndexOf('.');
            if(dotIndex>0&&dotIndex<filename.length()-1)
            {
                groupData.setSuffix_name(filename.substring(dotIndex+1));
                System.out.println(filename.substring(dotIndex+1));
            }
            else groupData.setSuffix_name("");
        }
        else groupData.setGroup_avatar(null);
        groupData.setGroup_id(data.getGroup_id());
        groupData.setGroup_name(name);
        groupData.setGroup_saying(saying);
        groupData.setGroup_friend_list(friendArryList);


        event massage=new event();
        massage.setType(MassageType.Change_Group_Information);
        massage.setT(groupData);

        new SendMassage().sendMassage(massage);
    }

    public void changeStage(GroupData newData)
    {
        GroupData old=data;
        if(newData.getCreater_id()!=null)
        {
            data.setCreater_id(newData.getCreater_id());
        }

        if(newData.getGroup_name()!=null)
        {
            data.setGroup_name(newData.getGroup_name());
        }

        if(newData.getGroup_avatar()!=null)
        {
            group_avatar.setImage(new Image(new ByteArrayInputStream(newData.getGroup_avatar())));
            data.setGroup_avatar(newData.getGroup_avatar());
        }

        if(newData.getGroup_saying()!=null)
        {
            group_saying.setText(newData.getGroup_saying());
            data.setGroup_saying(newData.getGroup_saying());
        }
        GroupData now=data;
        ChatMain chatMain=Main.AllContronller.getChatMainController();
        chatMain.changeGroup(old,now);
    }

    public void deleteGroup(ActionEvent actionEvent) throws IOException {
        //解散该群，是管理员做的事情
        event massage=new event();
        massage.setType(MassageType.Request_Delete_Group);
        data.setGroup_friend_list(friendArryList);
        massage.setT(data);

        new SendMassage().sendMassage(massage);
    }

    private File file=null;
    public void changeAvatar(MouseEvent mouseEvent) {
        Stage stage=new Stage();
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择头像");

        fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))
        );
        fileChooser.getExtensionFilters().addAll(
                new FileChooser.ExtensionFilter("All Images", "*.*"),
                new FileChooser.ExtensionFilter("JPG", "*.jpg"),
                new FileChooser.ExtensionFilter("GIF", "*.gif"),
                new FileChooser.ExtensionFilter("BMP", "*.bmp"),
                new FileChooser.ExtensionFilter("PNG", "*.png")
        );
        file= fileChooser.showOpenDialog(stage);

        if(file!=null) {
            Image image=new Image("file:"+file);
            group_avatar.setPreserveRatio(false);
            group_avatar.setImage(image);
            System.out.println(file);
        }
    }

    public void addFriend(GroupFriendData groupFriendData)
    {
        friendmap.put(groupFriendData.getId(),groupFriendData);
        friendArryList.add(groupFriendData);
        ChatMain chatMain=Main.AllContronller.getChatMainController();
        ArrayList<PrivateInformationData> privateInformationArrayList=chatMain.getPrivateInformationArry();
        chatMain.AddGroupFriendList(data.getGroup_id(),friendArryList);

        InviteOtherToGroup inviteOtherToGroup=Main.getAllContronller().getInviteOtherToGroupControllerById(groupFriendData.getGroup_id());
        if(inviteOtherToGroup!=null)
        {
            System.out.println("重新设置这个界面,看看我执行了吗");
            Platform.runLater(() -> {
             inviteOtherToGroup.setStage(privateInformationArrayList,friendmap);
            });
        }
        setAllFriend(friendArryList);
    }

    public void getInformation(int my_identity,GroupFriendData groupFriendData,PrivateInformation privateInformation)
    {
        int friend_identity=groupFriendData.getIdentity();
        if(my_identity==1&&friend_identity==2)
        {
            //群主看管理员的信息
            privateInformation.setOwnerLookAdmin(data,groupFriendData);
        }
        else if(my_identity==1&&friend_identity==3)
        {
            privateInformation.setOwnerLookPeople(data,groupFriendData);
        }
        else if(my_identity==2&&friend_identity==3)
        {
            privateInformation.setAdminLookPeople(data,groupFriendData);
        }
        else if(my_identity>=friend_identity)
        {
            privateInformation.setUpPosition(data,groupFriendData);
        }
    }

    public void ResultSendFile(event returnmassge)
    {
        if(returnmassge.getType().equals(MassageType.Return_Send_File_To_Group_Success))
        {
            MassageData massageData=(MassageData) returnmassge.getT();
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("成功");
            alert.setHeaderText(null);
            alert.setContentText("你分享的"+massageData.getFile_name()+"的文件成功");
            alert.showAndWait();

            addOneMassage(massageData);

            Platform.runLater(() -> {
                ChatMain chatMain=Main.AllContronller.getChatMainController();
                chatMain.getMsgList().addOneMsg(massageData.getReceiver(),massageData);
            });
        }
        else if(returnmassge.getType().equals(MassageType.Return_Send_File_To_Group_Fail))
        {
            Alert alert = new Alert(Alert.AlertType.INFORMATION);
            alert.setTitle("失败");
            alert.setHeaderText(null);
            alert.setContentText("你在群聊"+data.getGroup_id()+"分享的文件失败！");
            alert.showAndWait();
        }
    }

    public void CloseStage()
    {
        Stage stage=(Stage) emoji.getScene().getWindow();
        stage.close();
    }

    public static String getMD5(File file) throws IOException, NoSuchAlgorithmException
    {
        InputStream inputStream = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        int numRead = 0;
        while ((numRead = inputStream.read(buffer)) > 0) {
            md5.update(buffer, 0, numRead);
        }
        inputStream.close();
        byte[] md5Bytes = md5.digest();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < md5Bytes.length; i++) {
            if (Integer.toHexString(0xFF & md5Bytes[i]).length() == 1) {
                sb.append("0").append(Integer.toHexString(0xFF & md5Bytes[i]));
            } else {
                sb.append(Integer.toHexString(0xFF & md5Bytes[i]));
            }
        }
        return sb.toString();
    }
}
